package cdc.retrofit.demo;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import cdc.tools.Person;
import cdc.tools.PersonTools;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class PersonRequest {
	public static final String API_URL = "http://192.168.0.164:8080/api/";
	private Retrofit retrofit;
	private Api api;

	public PersonRequest() {
		retrofit = new Retrofit.Builder().baseUrl(API_URL).addConverterFactory(GsonConverterFactory.create()).build();
		api = retrofit.create(Api.class);
	}
	
	/**
	 * 上传json数据，并返回json数据
	 */
	public void upPerson() {
		Person person = PersonTools.initDefaultPerson();
		Gson gson = new GsonBuilder()  
				  .setDateFormat("yyyy-MM-dd HH:mm:ss")  
				  .create(); 
		String route = gson.toJson(person);// 通过Gson将Bean转化为Json字符串形式
		System.out.println(route);
		RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), route);
		Call<Person> call = api.createPerson(body);
		call.enqueue(new Callback<Person>() {

			@Override
			public void onResponse(Call<Person> call, Response<Person> response) {
				// TODO Auto-generated method stub
				request(call);
				System.out.println(response.code());
				Person person = response.body();
				System.out.println(person.toString());
			}

			@Override
			public void onFailure(Call<Person> call, Throwable t) {
				// TODO Auto-generated method stub

			}
		});
	}
	
	public void personid() {
		Call<Person> call = api.personid(1);
		call.enqueue(new Callback<Person>() {

			@Override
			public void onResponse(Call<Person> call, Response<Person> response) {
				// TODO Auto-generated method stub
				request(call);
				Person person = response.body();
				System.out.println(person.toString());

			}

			@Override
			public void onFailure(Call<Person> call, Throwable t) {
				// TODO Auto-generated method stub

			}
		});

	}
	
	private void request(Call<?> call) {
		Request request = call.request();
		headers(request);
		urlMethod(request);
	}

	private void urlMethod(Request request) {
		String method = request.method();
		String url = request.url().url().toString();
		System.out.println("method=" + method + ",url=" + url);
	}

	/**
	 * 打印请求头
	 * 
	 * @param request
	 */
	private void headers(Request request) {
		Headers headers = request.headers();
		int size = headers.size();
		System.out.println(size + "," + headers.toString());
		System.out.println("========header======================");
		for (int i = 0; i < size; i++) {
			String name = headers.name(i);
			String value = headers.value(i);
			System.out.println("header_name=" + name + ",header_value=" + value);
		}
		System.out.println("========header======================");
	}


}
